package com.cy.mall.comm.utils;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import java.io.OutputStream;

/**
 * @description: Json工具类
 * @author: Ocean
 * @create: 2018-04-24 16:02
 **/
@Slf4j
public class JsonObjectMapper {

    public static ObjectMapper OBJECT_MAPPER;

    static {
        log.info("JsonObjectMapper init...");
        OBJECT_MAPPER = SpringContextUtils.getBean(ObjectMapper.class);
    }

    public static <T> T read(String jsonResult, Class<T> valueType) {
        try {
            return OBJECT_MAPPER.readValue(jsonResult, valueType);
        } catch (Exception e) {
            log.error("JsonObjectMapper error:", e);
        }
        return null;
    }

    public static <T> T read(Object fromValue, Class<T> toValueType) {
        try {
            return OBJECT_MAPPER.convertValue(fromValue, toValueType);
        } catch (Exception e) {
            log.error("JsonObjectMapper error:", e);
        }
        return null;
    }

    public static String toJson(Object value) {
        if (value == null) {
            return null;
        }
        try {
            return OBJECT_MAPPER.writeValueAsString(value);
        } catch (Exception e) {
            log.error("JsonObjectMapper error:", e);
        }
        return null;
    }

    public static <T> T read(String jsonString, TypeReference<T> typeReference) {
        try {
            return OBJECT_MAPPER.readValue(jsonString, typeReference);
        } catch (Exception e) {
            log.error("JsonObjectMapper error:", e);
        }
        return null;
    }

    public static void write(OutputStream outputStream, Object object) {
        try {
            OBJECT_MAPPER.writeValue(outputStream, object);
        } catch (Exception e) {
            log.error("JsonObjectMapper error:", e);
        }
    }


}
